$(document).ready(function(){
	if (!$('#edit-wowid').val()) $('#node-form input[type=submit]').attr('disabled', 'disabled');
	
	$('#edit-wowhead-query').data("results", {} );

	$('#edit-wowhead-query').keyup(function(e){
		var query = $(this).val().toLowerCase();
		if (typeof $(this).data("results")[query] == 'object'){
			//We've already stored this query's info.  Retrieve it.
			var results = $(this).data("results");
			mewdkp_itemResult(results[query]);
			clearTimeout($(this).data("keytimer"));
		} else {	
			$('#node-form input[type=submit]').attr('disabled', 'disabled');
			clearTimeout($(this).data("keytimer"));
			var t = setTimeout("mewdkp_itemRequest()", 600);
			$(this).data("keytimer", t);
		}
	});
});


function mewdkp_itemRequest(){
	var query = $('#edit-wowhead-query').val().toLowerCase();
	$('#wowhead-display-content').html('Searching WowHead...');
	$('#node-form input[type=submit]').attr('disabled', 'disabled');
	$.ajax({
		url: "http://system3.mewcode.com/mewdkp/response/wowhead/"+query, 
		type: "GET",
		dataType: "json",
		success: function(data){
			if (data.wowid > 0){
				var results = $('#edit-wowhead-query').data("results");
				results[query] = data;
				$('#edit-wowhead-query').data("results", results);
				mewdkp_itemResult(data);
			} else {
				$('#wowhead-display-content').html("No item found.");
				$('#node-form input[type=submit]').attr('disabled', 'disabled');
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			$('#wowhead-display-content').html("No item found.");
		}
  });
}

function mewdkp_itemResult(data){
	$('#wowhead-display-content').html(data.htmltooltip);
	$('#edit-wowid').val(data.wowid);
	$('#node-form input[type=submit]').removeAttr('disabled');
}
